package com.example.ending_demo.servlet;

import com.example.ending_demo.model.Address;
import com.example.ending_demo.service.AddressService;

import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/AddressEditServlet")
public class AddressEditServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String addr_id =request.getParameter("id");
        String addr_username = request.getParameter("username");
        String addr_phone = request.getParameter("phone");
        String addr_email = request.getParameter("email");
        String addr_address = request.getParameter("address");

        Address obj = new Address();
        obj.setAddress_id(Integer.parseInt(addr_id));
        obj.setAddr_username(addr_username);
        obj.setAddr_phone(addr_phone);
        obj.setAddr_email(addr_email);
        obj.setAddress(addr_address);

        AddressService addrSvc = new AddressService();

        try {
            int result = addrSvc.updateAddress(obj);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

//        response.sendRedirect("AddressListServlet");
        response.sendRedirect("AddressListPageServlet");


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String address_id = request.getParameter("id");

        AddressService addSvc = new AddressService();
        Address obj = null;
        try {
            obj = addSvc.getAddressByAddressID(Integer.parseInt(address_id));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        request.setAttribute("addr",obj);
        RequestDispatcher dispatcher = request.getRequestDispatcher("address_edit.jsp");
        dispatcher.forward(request,response);
    }
}